﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web.UI.WebControls;
using System.Web;
using System.Web.UI;
using System.Security.AccessControl;

namespace CSP.Common.Providers
{
    /// <summary>
    /// 图片上传类、可生成略缩图、水印等
    /// </summary>
    public class ImageProvider
    {
        private bool _Random_name = true;  //是否使用随机名称

        private bool _IsCreateImg = true;  //是否生成缩略图。

        private string _FileType = "jpg/gif/bmp/png"; //所支持的上传类型用"/"隔开

        private string _SavePath = string.Empty;    //保存文件的实际路径

        private int _sHeight = 300;   //设置生成缩略图的高度

        private int _sWidth = 300;    //设置生成缩略图的宽度

        private int _lHeigth = 0;  //设置生成上传服务器的图片

        private int _lWidth = 0;  //设置生成上传服务器的图片

        private HttpPostedFile File_Upload; //上传文件。

        private int _Error = 0;//返回上传状态。

        private string _New_FileName = string.Empty; //随机产生得新图片名称

        private string _New_FileName_S = string.Empty; //随机产生得新缩略图名称

        private string _New_FileName_L = string.Empty; //临时随机产生得新图片名称、为加水印前、如果加水印后该文件自动删除

        private string _New_ImageName = string.Empty; //上传服务器后的新图片名称

        private bool _IsDraw = false;//设置是否加水印

        private int _DrawString_x = 200;//绘制文本的Ｘ坐标（右下角）

        private int _DrawString_y = 30;//绘制文本的Ｙ坐标（右下角）

        private string _AddText = "设置水印内容";//设置水印内容

        private string _Font = "Verdana"; //设置水印字体

        private int _FontSize = 16; //设置水印字大小


        /// <summary>
        /// 是否使用随机名称，是为:TRUE;不使用则FLASE
        /// </summary>
        public bool Random_name
        {
            get { return _Random_name; }
            set { _Random_name = value; }
        }

        /// <summary>
        /// 获取随机产生得新图片名称
        /// </summary>
        public string New_FileName
        {
            get { return _New_FileName; }
        }

        /// <summary>
        /// 上传服务器后的新图片名称
        /// </summary>
        public string New_ImageName
        {
            get { return _New_ImageName; }
        }

        /// <summary>
        /// 随机产生得新缩略图名称
        /// </summary>
        public string New_FileName_S
        {
            get { return _New_FileName_S; }
        }

        /// <summary>
        /// //上传控件。
        /// </summary>
        public HttpPostedFile _File_Upload
        {
            get { return File_Upload; }
            set { File_Upload = value; }
        }

        /// <summary>
        /// 是否生成缩略图
        /// </summary>
        public bool IsCreateImg
        {
            get { return _IsCreateImg; }
            set { _IsCreateImg = value; }
        }

        /// <summary>
        /// 所支持的上传类型用"/"隔开
        /// </summary>
        public string FileType
        {
            set { _FileType = value; }
        }

        /// <summary>
        /// 绘制文本的Ｘ坐标（左上角）
        /// </summary>
        public int DrawString_x
        {
            get { return _DrawString_x; }
            set { _DrawString_x = value; }
        }

        /// <summary>
        /// 绘制文本的Ｙ坐标（左上角）
        /// </summary>
        public int DrawString_y
        {
            get { return _DrawString_y; }
            set { _DrawString_y = value; }
        }

        /// <summary>
        /// 是否加水印
        /// </summary>
        public bool IsDraw
        {
            get { return _IsDraw; }
            set { _IsDraw = value; }
        }

        /// <summary>
        /// 设置文字水印字体
        /// </summary>
        public string Font
        {
            get { return _Font; }
            set { _Font = value; }
        }

        /// <summary>
        /// 设置文字水印字的大小
        /// </summary>
        public int FontSize
        {
            get { return _FontSize; }
            set { _FontSize = value; }
        }

        /// <summary>
        /// 保存文件的实际路径
        /// </summary>
        public string SavePath
        {
            set { _SavePath = value; }
            get { return _SavePath.Replace(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, ""); }
        }

        /// <summary>
        /// 设置缩略图的宽度
        /// </summary>
        public int sWidth
        {
            get { return _sWidth; }
            set { _sWidth = value; }
        }

        /// <summary>
        /// 指定原始图片图片缩放的宽度，如果为0 代表不缩略原始图片
        /// </summary>
        public int LWidth
        {
            get { return _lWidth; }
            set { _lWidth = value; }
        }

        /// <summary>
        /// 设置文字水印内容
        /// </summary>
        public string AddText
        {
            get { return _AddText; }
            set { _AddText = value; }
        }

        /// <summary>
        /// 设置缩略图的高度
        /// </summary>
        public int sHeight
        {
            get { return _sHeight; }
            set { _sHeight = value; }
        }

        /// <summary>
        /// Error返回值，1、没有上传的文件。2、类型不允许。3、大小超限。4、未知错误。0、上传成功。
        /// </summary>
        public int Error
        {
            get { return _Error; }
        }

        public void Save_AS()
        {
            if (File_Upload == null)
            {
                _Error = 1;
                return;
            }

            string Ext = GetExt(File_Upload.FileName);

            if (!IsUpload(Ext))
            {
                _Error = 2;
                return;
            }


            if (!Directory.Exists(_SavePath))
            {
                Directory.CreateDirectory(_SavePath);
            }

            if (!Pic_Up())
            {
                return;
            }

            if (_IsCreateImg)
            {
                MakeThumbnail(_New_FileName, _New_FileName_S, _sWidth, _sHeight, "W");
            }

            if (_IsDraw)
            {
                AddShuiYinWord(_New_FileName, _New_FileName);
            }

            _Error = 0;

        }

        private bool Pic_Up()
        {

            _New_ImageName = GetNewFileName(File_Upload.FileName);

            _New_FileName_S = _SavePath + "S_" + _New_ImageName;

            _New_FileName_L = _SavePath + "L_" + _New_ImageName;

            _New_FileName = _SavePath + _New_ImageName;

            try
            {
                File_Upload.SaveAs(_New_FileName);
                if (_lWidth != 0)
                {
                    MakeThumbnail(_New_FileName, _New_FileName, _lWidth, _sHeight, "WA");
                }

                return true;
            }
            catch (Exception ex)
            {
                _Error = 4;
                throw ex;
            }
        }


        /**/
        /// <summary> 
        /// 生成缩略图 
        /// </summary> 
        /// <param name="originalImagePath">源图路径（物理路径）</param> 
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param> 
        /// <param name="width">缩略图宽度</param> 
        /// <param name="height">缩略图高度</param> 
        /// <param name="mode">生成缩略图的方式</param> 
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形） 
                    break;
                case "W"://指定宽，高按比例 
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "WA"://指定宽，高按比例（原始图片的宽度大于指定宽度时）
                    if (width < originalImage.Width)
                    {
                        toheight = originalImage.Height * width / originalImage.Width;
                    }
                    else
                    {
                        towidth = originalImage.Width;
                        toheight = originalImage.Height;
                    }
                    break;
                case "H"://指定高，宽按比例 
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形） 
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片 
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板 
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法 
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度 
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充 
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分 
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
            new System.Drawing.Rectangle(x, y, ow, oh),
            System.Drawing.GraphicsUnit.Pixel);

            try
            {
                if (originalImagePath == thumbnailPath)
                {
                    originalImage.Dispose();
                    File.Delete(originalImagePath);
                }
                //以jpg格式保存缩略图 
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        /// <summary>
        /// 复制并生成新文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public string CopyAndCreateNewImg(string fileName)
        {
            string newFileName = "";
            if (File.Exists(fileName))
            {
                newFileName = fileName.Substring(0, fileName.LastIndexOf('/') + 1) + GetNewFileName(fileName);
                File.Copy(fileName, newFileName);
            }
            string thumbnailFileName = fileName.Substring(0, fileName.LastIndexOf('/') + 1) + "S_" + fileName.Substring(fileName.LastIndexOf('/') + 1);
            if (File.Exists(thumbnailFileName))
            {
                string newThumbnailFileName = newFileName.Substring(0, newFileName.LastIndexOf('/') + 1) + "S_" + newFileName.Substring(newFileName.LastIndexOf('/') + 1);
                File.Copy(thumbnailFileName, newThumbnailFileName);
            }
            return newFileName;
        }

        /**/
        /// <summary> 
        /// 在图片上增加文字水印 
        /// </summary> 
        /// <param name="Path">原服务器图片路径</param> 
        /// <param name="Path_sy">生成的带文字水印的图片路径</param> 
        protected void AddShuiYinWord(string Path, string Path_sy)
        {

            System.Drawing.Image image = System.Drawing.Image.FromFile(Path);

            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);

            g.DrawImage(image, 0, 0, image.Width, image.Height);

            System.Drawing.Font f = new System.Drawing.Font(_Font, _FontSize);

            System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.White);

            g.DrawString(_AddText, f, b, image.Width - _DrawString_x, image.Height - _DrawString_y);

            g.Dispose();

            image.Save(Path_sy);

            image.Dispose();

            File.Delete(Path);
        }

        private string GetNewFileName(string FileName)
        {
            //跟据文件名产生一个由时间+随机数组成的一个新的文件名 
            string newfilename = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString()
            + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString()
            + DateTime.Now.Second.ToString() + DateTime.Now.Minute.ToString()
            + DateTime.Now.Millisecond.ToString()
                //+ rand.Next(1000).ToString() 
            + FileName.Substring(FileName.LastIndexOf("."), FileName.Length - FileName.LastIndexOf("."));
            return newfilename;
        }

        //检查上传的文件的类型，是否允许上传。
        private bool IsUpload(string Ext)
        {
            Ext = Ext.Replace(".", "");
            bool b = false;
            string[] arrFileType = _FileType.Split('/');
            foreach (string str in arrFileType)
            {
                if (str.ToLower() == Ext.ToLower())
                {
                    b = true;
                    break;
                }
            }
            return b;
        }

        //获取文件的后缀名
        private string GetExt(string path)
        {
            return Path.GetExtension(path);
        }

        public enum ThumbnailType
        {
            /// <summary>
            /// 指定宽，高按比例 
            /// </summary>
            W = 0,

            /// <summary>
            /// 指定高宽缩放（可能变形） 
            /// </summary>
            WH = 1,

            /// <summary>
            /// 指定高，宽按比例 
            /// </summary>
            H = 2,

            /// <summary>
            /// 指定高宽裁减（不变形）
            /// </summary>
            Cut = 3
        }

    }
}
